#!/opt/php/bin/php -d display_errors=1
<?php
require_once 'TVB/Message/BaseConsumer.php';
require_once 'TVB/Message/MessageHelper.php';

require_once 'TVB/mytvplus/portal_service/common/bootstrap.php';
require_once 'TVB/mytvplus/portal_service/common/AppConfiguration.class.php';
require_once 'TVB/mytvplus/portal_service/common/util/PublishHelper.php';
require_once 'TVB/mytvplus/portal_service/common/model/Db3Model.php';

date_default_timezone_set('UTC');

class PublishDb3AndPortal extends BaseConsumer
{
    protected function process(Stomp_Frame $message)
    {
		$start_time = microtime(TRUE);

		echo "\n\n\n" , date('Y-m-d H:i:s') , ": Start import data ...";
		$data = json_decode(json_encode($message->map),1);
		$action = strtolower($data['action']);
		$data['callback_data'] = json_decode(bzdecompress(base64_decode($data['callback_data'])),1);

		$message = '';
		$return  = true;
		$mailto  = CommonUtils::getAdminMail() . ',' . $data['callback_data']['operation_user'];

		#### Check Error ####
		echo "\n--> Action[$action] Event[Check VI/II Error] Start.\n";
		if(!empty($data['messages'])){ // has error; messages[error_vi|error_ii][1|2][] = $vi_id|$ii_id;
			foreach($data['messages'] as $media_type=>$error_data)
			{
				$media = ($media_type=='error_vi') ? 'video' : 'image';
				foreach($error_data as $error_type=>$media_ids)
				{
					$ids = implode(',',$media_ids);
					$error = ($error_type=='1') ? 'export' : 'distribute';
					$message .= strpos($ids,',')?("Could not $error these {$media}s:$ids\n"):("Could not $error this $media:$ids\n");
				}
			}
			$return = false;
			$mailto.= ','.CommonUtils::getAdminMail('AVTeam');
		}
		echo "--> Action[$action] Event[Check VI/II Error] End.\n";

		#### Insert DB3 ####
		echo "\n--> Action[$action] Event[Insert DB3] Start.\n";
		if($return){
			$db3 = CommonUtils::getDbConn(true,'pdes_db3');
			$db3->getDbHandle()->beginTransaction();
			try{
                if('publish' == $action || 'p_publish' == $action)
                {
					delete_db3_data($data,$db3);
					$db3_data = merge_data_and_update_db3($data,$db3); // coding by vanni
                    if(!call_mis_api($data)){       // coding by davis
                        $message .= "Can't call mis api\n";
                    }
				}else{
					delete_db3_data($data,$db3);
				}
				$db3->getDbHandle()->commit();
			}catch(Exception $e){
				$db3->getDbHandle()->rollBack();
				$message .= 'Update db3 error:'.$e->getMessage()."\n".$e->getTraceAsString()."\n\n";
				$return = false;
			}
		}

		echo "--> Action[$action] Event[Insert DB3] End.\n";

		echo "\n--> Action[$action] Event[Insert Portal DB & Send XML] Start.\n";
		#### Insert Protal DB And Send XML ####
		if ($return && ($action == 'p_publish' || $action == 'p_unpublish')) {
			Model::$dbo['r'] = Model::$dbo['w'];
			Model::$dbo['w']->beginTransaction();
			$portal = new P_Portal;

			try {
				$portal->setData($data);
				$portal->recevieStart();
				Model::$dbo['w']->commit();
			} catch (Exception $e) {
				Model::$dbo['w']->rollback();
				$message .= 'PortalReceive error:'.print_r($e, 1)."\n\n";
				$return  = false;
			}
		}
		echo "--> Action[$action] Event[Insert Portal DB & Send XML] End.\n";

		#### Update DB1 Status ####
		echo "\n--> Action[$action] Event[Update DB1 & Delete change_log if need.] Start.\n";
		$db1 = CommonUtils::getDbConn(true,'pdes_db1');
		$db1->getDbHandle()->beginTransaction();
		try{
			update_db1($data,$db1,$return);  // coding by vanni
			if($return){
				delete_change_log($data);
			}else{
				reset_change_log($data);
			}
			$db1->getDbHandle()->commit();
		}catch(Exception $e){
			$db1->getDbHandle()->rollBack();
			$message .= 'Update db1 error'.$e->getMessage()."\n".$e->getTraceAsString()."\n\n";
		}
		echo "--> Action[$action] Event[Update DB1 & Delete change_log] End.\n";


		if($message){
			mail($mailto,'PublishDb3AndPortal Consumer Error',$message);
		}

		$end_time = microtime(TRUE);
		$time_elapsed = $end_time - $start_time;
		echo date('Y-m-d H:i:s') . ": Import data completed. Time used: {$time_elapsed}s\n";

		return true;
	}
}

$cons = new PublishDb3AndPortal(AC::CONFIG_MQ, 'PublishDb3AndPortal');

try{
	$cons->run();
}catch(Stomp_Exception $e){
	mail(CommonUtils::getAdminMail(),"PublishDb3AndPortal Consumer Error:MQ Server Error!",print_r($e,1));
}
?>
